package com.wkq.jdbctemplate.dao;

import com.wkq.jdbctemplate.commons.RecordRowMapper;
import com.wkq.jdbctemplate.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class GoodsDao {
    private static final com.wkq.jdbctemplate.commons.RecordRowMapper RecordRowMapper = new RecordRowMapper();
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     *
     * @param goods
     * @return
     */
    public int insert(Goods goods) {
        System.out.println("goods = " + goods);
        int result = jdbcTemplate.update("insert into goods(name,price,pic) values(?,?,?)", goods.getName(), goods.getPrice(), goods.getPic());
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Long id) {
        int result = jdbcTemplate.update("delete from goods where id = ?", id);
        return result;
    }

    /**
     * 跟新
     *
     * @param goods
     * @return
     */
    public int update(Goods goods) {
        int result = jdbcTemplate.update("update goods set name=?,price=?,pic=? where id=?", goods.getName(), goods.getPrice(), goods.getPic(), goods.getId());
        return result;
    }

    /**
     * 按id查询
     *
     * @param id
     * @return
     */
    public Object getById(Long id) {
        return jdbcTemplate.queryForObject("select * from goods where id =?", RecordRowMapper, id);
    }

/*
    public Goods getById(Long id) {
        return jdbcTemplate.queryForObject("select * from goods where id =?", new RowMapper<Goods>() {
            @Override
            public Goods mapRow(ResultSet rs, int rowNum) throws SQLException {
                Goods goods = new Goods();
                goods.setId(rs.getLong("id"));
                goods.setName(rs.getString("name"));
                goods.setPic(rs.getString("pic"));
                goods.setPrice(rs.getString("price"));
                return goods;
            }
        }, id);
    }*/

    /**
     * 查询商品列表
     *
     * @return
     */
    public List<Goods> getList() {
        return jdbcTemplate.queryForList("select * from goods", Goods.class);
    }

    //    public List<Goods> list() {
//        return jdbcTemplate.query("select * from goods ", (rs, rowNum) -> {
//            Goods goods = new Goods();
//            goods.setId(rs.getLong("id"));
//            goods.setName(rs.getString("name"));
//            goods.setPic(rs.getString("pic"));
//            goods.setPrice(rs.getString("price"));
//            return goods;
//        });
//    }
    public List<Goods> list() {
        return jdbcTemplate.query("select * from goods ", RecordRowMapper);
    }
}
